package com.aaa.dao.impl;

import com.aaa.dao.Flim_OrderDao;
import com.aaa.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Controller;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Controller
public class Flim_OrderDaoImpl implements Flim_OrderDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public RowMapper<Flim_Order> rowMapper=new RowMapper<Flim_Order>() {
        public Flim_Order mapRow(ResultSet resultSet, int i) throws SQLException {
            Flim_Order flim_order=new Flim_Order();
            flim_order.setId(resultSet.getLong("id"));
            flim_order.setSeats(resultSet.getString("seats"));
            flim_order.setState(resultSet.getString("state"));
            User user = new User();
            user.setId(resultSet.getInt("id"));
            user.setUsername(resultSet.getString("username"));
            flim_order.setUser(user);
            Movie movie=new Movie();
            movie.setId(resultSet.getLong("id"));
            movie.setName(resultSet.getString("name"));
            flim_order.setMovie(movie);
            Mhall mhall=new Mhall();
            mhall.setId(resultSet.getLong("hid"));
            mhall.setName(resultSet.getString("hname"));
            flim_order.setMhall(mhall);
            Nofs nofs=new Nofs();
            nofs.setNid(resultSet.getLong("nid"));
            nofs.setEdate(resultSet.getString("edate"));
            nofs.setSdate(resultSet.getString("sdate"));
            nofs.setPrice(resultSet.getString("price"));
            flim_order.setNofs(nofs);
            return flim_order;
        }
    };
    public List<Flim_Order> listPage(String keyword, Integer offset, Integer limit) {
        String sql="select o.*,u.*,n.*,h.*,m.* from flim_order o left join user u on o.uid = u.id \n" +
                "                                left join nofs n on o.nid = n.nid \n" +
                "                                left join mhall h on o.hid = h.hid \n" +
                "                                left join movie m on o.mid = m.id \n" +
                "                                 where  u.username like ? order by o.id desc limit ?,? " ;
        List<Flim_Order> query = this.jdbcTemplate.query(sql, rowMapper,"%" + keyword + "%", offset, limit);
        return query;
    }

    public Integer count(String keyword) {
        String sql = "select count(o.id) as c from flim_order o where o.seats like ? ";
        Integer result = this.jdbcTemplate.queryForObject(sql, new RowMapper<Integer>() {
            public Integer mapRow(ResultSet resultSet, int i) throws SQLException {
                return resultSet.getInt("c");
            }
        },"%"+keyword+"%");
        return  result;
    }
}
